package com.storage.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.core.text.Convert;
import com.storage.common.enums.OwnerType;
import com.storage.common.enums.RoleType;
import com.storage.common.enums.UserAndAgentLevelType;
import com.storage.common.jpush.JiGuangPushUtil;
import com.storage.common.utils.WxUtil;
import com.storage.system.domain.*;
import com.storage.system.mapper.*;
import com.storage.system.service.IStorageShopService;
import com.storage.system.service.IStorageUserAgentService;
import com.storage.system.service.IStorageUserService;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户 服务层实现
 *
 * @author storage
 * @date 2019-08-18
 */
@Service
public class StorageUserServiceImpl implements IStorageUserService {

    private static Pattern PHONE_PATTERN = Pattern.compile("^1[3456789]\\d{9}");

    @Autowired
    private StorageUserMapper storageUserMapper;

    @Autowired
    private StorageUserAgentMapper storageUserAgentMapper;

    @Autowired
    private IStorageUserAgentService storageUserAgentService;

    @Autowired
    private IStorageShopService storageShopService;

    @Autowired
    private StorageShopMapper storageShopMapper;

    @Autowired
    private StorageBrandMapper storageBrandMapper;

    @Autowired
    private StorageNoticeMessageMapper storageNoticeMessageMapper;

    @Autowired
    private StorageProcurementOrderMapper storageProcurementOrderMapper;

    @Autowired
    private StorageProductMapper storageProductMapper;

    /**
     * 查询用户信息
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @Override
    public StorageUser selectStorageUserById(Long id) {
        return storageUserMapper.selectStorageUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param storageUser 用户信息
     * @return 用户集合
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageUserList(StorageUser storageUser, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;
        // 查询查询分页数据
        List<StorageUser> users = storageUserMapper.queryPageList(storageUser, start, pageSize);
        // 查询totalCount
        Long totalCount = storageUserMapper.queryPageCount(storageUser);

        TableDataInfo pageList = new TableDataInfo(users, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 新增用户
     *
     * @param currentUser
     * @param addUserObj
     * @return
     */
    @Override
    public AjaxResult insertStorageUser(StorageUser currentUser, StorageUser addUserObj) {
        if (!PHONE_PATTERN.matcher(addUserObj.getPhone()).matches()) {
            return AjaxResult.error("非法的电话号码");
        } else if (storageUserMapper.selectUserByPhoneNumber(addUserObj.getPhone()) != null) {
            return AjaxResult.error("当前电话已经已经存在");
        }

        if (StringUtils.isNotBlank(addUserObj.getNickName())) {
            addUserObj.setNickName(EmojiParser.parseToAliases(addUserObj.getNickName()));
        }

        storageUserMapper.insertStorageUser(addUserObj);
        return AjaxResult.success("操作成功", selectStorageUserById(addUserObj.getId()));
    }

    /**
     * 修改用户
     *
     * @param storageUser 用户信息
     * @return 结果
     */
    @Override
    public ServiceResponse<StorageUser> updateStorageUser(StorageUser currentUser, StorageUser storageUser) {
        storageUserMapper.updateStorageUser(storageUser);
        if (storageUser.getId() == null) {
            storageUser.setId(currentUser.getId());
        }

        if (StringUtils.isNotBlank(storageUser.getNickName())) {
            storageUser.setNickName(EmojiParser.parseToAliases(storageUser.getNickName()));
        }

        return new ServiceResponse<>(true, storageUserMapper.selectStorageUserById(storageUser.getId()), null);
    }

    /**
     * 删除用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStorageUserByIds(String ids) {
        return storageUserMapper.deleteStorageUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public StorageUser selectUserByPhoneNumber(String phoneNumber) {
        return storageUserMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public StorageUser selectUserByEmail(String email) {
        return storageUserMapper.selectUserByEmail(email);
    }

    /**
     * 根据微信 code 查询用户信息
     *
     * @param wxCode
     * @return
     */
    @Override
    public StorageUser selectStorageUserByWxCode(String wxCode) {
        StorageUser storageUser = storageUserMapper.selectUserByWxCode(wxCode);
        if (storageUser != null) {
            return storageUser;
        }

        WxUtil util = new WxUtil();
        WxUtil.WxUserInfo wxUserInfo = util.getUserInfo(wxCode);
        if (wxUserInfo != null) {
            storageUser = new StorageUser();
            storageUser.setAvatar(wxUserInfo.getHeadimgurl());
            storageUser.setNickName(wxUserInfo.getNickname());
            int result = storageUserMapper.insertStorageUser(storageUser);
            if (result == 1) {
                storageUser = storageUserMapper.selectStorageUserById(storageUser.getId());
                return storageUser;
            }
        }
        return null;
    }

    /**
     * 查询用户-代理商列表(用于上下级对账、上下级管理)
     *
     * @param currentUser
     * @param level
     * @return
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageUserAgentList(StorageUser currentUser, Integer level, String type, Integer pageNum, Integer pageSize) {

        StorageUserAgent storageUserAgent = new StorageUserAgent();
        storageUserAgent.setUserId(currentUser.getId());
        if (level != null) {
            storageUserAgent.setLevel(level);
        }
        if (StringUtils.isNotBlank(type)) {
            storageUserAgent.setType(type);
        } else {
            // 只查询代理商上下级，不查询店铺
            storageUserAgent.setType(OwnerType.AGENT.name());
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;

        // 查询查询分页数据
        List<StorageUserAgent> agents = storageUserAgentMapper.queryPageList(storageUserAgent, start, pageSize);
        // 查询totalCount
        Long totalCount = storageUserAgentMapper.queryPageCount(storageUserAgent);

        for (StorageUserAgent agent : agents) {
            if (StringUtils.isNotBlank(type)) {
                StorageShop storageShop = storageShopMapper.selectStorageShopById(agent.getAgentId());
                if (storageShop != null) {
                    agent.setAgentName(storageShop.getShopName());
                }
            } else {
                StorageUser storageUser = storageUserMapper.selectStorageUserById(agent.getAgentId());
                if (storageUser != null) {
                    agent.setAgentName(storageUser.getNickName());
                    agent.setAgentInvitationCode(storageUser.getPhone());
                    agent.setAddress(storageUser.getAddress());
                }
            }
        }
        TableDataInfo pageList = new TableDataInfo(agents, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 新增保存用户-代理商
     */
    @Override
    public ServiceResponse<StorageUserAgent> insertStorageUserAgent(StorageUser currentUser, StorageUserAgent storageUserAgent) {
        // 根据邀请码查询代理商用户信息
        StorageUser agent = storageUserMapper.selectUserByPhoneNumber(storageUserAgent.getAgentInvitationCode());
        if (agent == null) {
            return new ServiceResponse<>(false, null, "代理商不存在");
        }

        // 禁止添加超级管理员为下级代理商,可以添加超级管理员为上级代理商
        if (agent.getRole() == RoleType.ADMIN.getValue() && storageUserAgent.getLevel() == 1) {
            return new ServiceResponse<>(false, null, "禁止添加超级管理员为下级代理商");
        }

        StorageUserAgent userAgent = new StorageUserAgent();
        userAgent.setAgentId(agent.getId());
        userAgent.setUserId(currentUser.getId());
        List<StorageUserAgent> existAgents = storageUserAgentMapper.selectStorageUserAgentList(userAgent);
        if (existAgents != null && existAgents.size() > 0) {
            String info = UserAndAgentLevelType.valueOf(existAgents.get(0).getLevel()).getDesc();
            return new ServiceResponse<>(false, null, String.format("当前代理商已经是您的【%s】，请勿重复添加", info));
        }

        String nickName = currentUser.getNickName();
        if (StringUtils.isNotBlank(nickName)) {
            nickName = EmojiParser.parseToAliases(nickName);
        }

        // 持久化消息记录
        String title = String.format("%s 成为你的%s级代理商", nickName, storageUserAgent.getLevel() == 1 ? "上" : "下");

        String phone = agent.getPhone();
        Long userId = agent.getId();
        StorageNoticeMessage noticeMessage = new StorageNoticeMessage(userId, phone, null, title);
        int result = storageNoticeMessageMapper.insertStorageNoticeMessage(noticeMessage);
        if (result == 1) {
            // 查询系统消息的同时并极光推送
            JiGuangPushUtil.pushNotice(phone, title, null, noticeMessage.getId());
        }

        storageUserAgentService.addUserAndAgentRelationship(currentUser.getId(), agent.getId(), storageUserAgent.getLevel(), storageUserAgent.getAcceptBrand());
        return new ServiceResponse<>(true, storageUserAgentMapper.selectStorageUserAgentById(storageUserAgent.getId()), null);
    }

    @Override
    public AjaxResult updateStorageUserAgent(StorageUser currentUser, StorageUserAgent storageUserAgent) {
        storageUserAgent.setUserId(currentUser.getId());
        storageUserAgentMapper.updateStorageUserAgent(storageUserAgent);
        return AjaxResult.success();
    }

    @Override
    public StorageUser selectUserByBusinessCode(String businessCode) {
        return storageUserMapper.selectStorageUserByBusinessCode(businessCode);
    }

    @Override
    public ServiceResponse<Boolean> deleteStorageUserAgentByIds(StorageUser currentUser, Integer level, String ids) {
        if (StringUtils.isBlank(ids)) {
            return new ServiceResponse<>(false, null, "删除id不能为空");
        }

        StringBuilder stringBuilder = new StringBuilder();
        String[] idArr = ids.split(",");
        for (String agentId : idArr) {
            StorageUserAgent userAgent = storageUserAgentMapper.selectStorageUserAgentById(Long.parseLong(agentId));
            StorageUserAgent downAgent = null;
            StorageUserAgent upAgent = null;
            if (level == UserAndAgentLevelType.DOWN.getValue()) {
                // 删除下级代理商
                upAgent = userAgent;
                downAgent = storageUserAgentMapper.selectUserAgent(upAgent.getAgentId(), upAgent.getUserId(), UserAndAgentLevelType.UP.getValue(), OwnerType.AGENT.name());
            } else if (level == UserAndAgentLevelType.UP.getValue()) {
                // 删除上级代理商
                downAgent = userAgent;
                upAgent = storageUserAgentMapper.selectUserAgent(downAgent.getAgentId(), downAgent.getUserId(), UserAndAgentLevelType.DOWN.getValue(), OwnerType.AGENT.name());
            }

            if (downAgent == null || upAgent == null) {
                return new ServiceResponse<>(false, null, "删除失败");
            }

            if (downAgent.getPaymentMoney() != null && upAgent.getPaymentMoney() != null
                    && (!downAgent.getPaymentMoney().equals(new BigDecimal(0)) || !upAgent.getPaymentMoney().equals(new BigDecimal(0)))) {
                stringBuilder.append(String.format("[%s] 不能删除，与代理商之间还存在 [%s] 结算金额未结清; ", agentId, upAgent.getPaymentMoney()));
                continue;
            }

            // 删除店铺已经对应店铺与代理商之间的上下级关联关系
            storageUserAgentMapper.deleteStorageUserAgentById(downAgent.getId());
            storageUserAgentMapper.deleteStorageUserAgentById(upAgent.getId());
        }

        if (stringBuilder.toString().length() > 0) {
            return new ServiceResponse<>(false, null, stringBuilder.toString());
        }

        return new ServiceResponse<>(true, null, "删除成功");
    }

    /**
     * 更新是否开放库存查看状态给指定代理商
     *
     * @param agentId 代理商id
     * @param show    代理商查看当前用户库存权限: 0-不允许代理商查看;1-允许代理商查看库存
     * @return
     */
    @Override
    public AjaxResult markStockShowStatus(StorageUser storageUser, Long agentId, int show) {

        return null;
    }

    /**
     * 获取店铺创建人信息
     *
     * @param storageUser
     * @return
     */
    @Override
    public ServiceResponse<StorageUser> getShopCreatorInfo(StorageUser storageUser) {
        if (!RoleType.isWorker(storageUser.getRole())) {
            return new ServiceResponse<>(false, null, "进店铺人员具有接口操作权限");
        }

        StorageShop storageShop = storageShopService.selectStorageShopById(storageUser.getShopId());
        if (storageShop == null) {
            return new ServiceResponse<>(false, null, "当前人员所属店铺不存在");
        }

        StorageUser createShopUserInfo = storageUserMapper.selectStorageUserById(storageShop.getCreateUserId());
        if (createShopUserInfo == null) {
            return new ServiceResponse<>(false, null, "店铺创建人不存在");
        }

        return new ServiceResponse<>(true, createShopUserInfo, null);
    }

    /**
     * 查询业务员列表
     *
     * @param storageUser
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageBusinessUserList(StorageUser currentUser, StorageUser storageUser, Integer pageNum, Integer pageSize) {
        // 判断是否是管理员
        String error= "";
        if (!RoleType.isAdmin(currentUser.getRole())) {
            error = "不具备该接口操作权限";
        } else if (storageUser.getRole() != RoleType.BUSINESS_USER.getValue()) {
            error = "仅提供查询业务员列表操作";
        }

        if (StringUtils.isNotBlank(error)) {
            return new ServiceResponse<>(false, null, error);
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;
        // 查询查询分页数据
        List<StorageUser> businessUserList = storageUserMapper.queryPageList(storageUser, start, pageSize);
        // 查询totalCount
        Long totalCount = storageUserMapper.queryPageCount(storageUser);

        for (StorageUser user : businessUserList) {
            StorageUser condition = new StorageUser();
            condition.setSource(user.getBusinessCode());
            List<StorageUser> recommendList = storageUserMapper.selectStorageUserList(condition);
            if (recommendList == null) {
                user.setRecommend(new ArrayList<>());
            } else {
                user.setRecommend(recommendList);
            }
        }

        TableDataInfo pageList = new TableDataInfo(businessUserList, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 获取指定代理商开发给当前用户的品牌
     *
     * @param level
     * @param agentId
     * @return
     */
    @Override
    public ServiceResponse<List<StorageBrand>> getAgentBrands(StorageUser storageUser, Integer level, Long agentId) {
        if (RoleType.isWorker(storageUser.getRole())) {
            // 当前用户时候店铺用户时候直接返回
            return new ServiceResponse<>(true, new ArrayList<>(), null);
        }
        StorageUserAgent agent = storageUserAgentMapper.selectUserAgent(agentId, storageUser.getId(), level, OwnerType.AGENT.name());
        if (agent == null) {
            return new ServiceResponse<>(false, null, "用户与代理商上不存在上下级关系!");
        } else if (StringUtils.isBlank(agent.getAcceptBrand())) {
            return new ServiceResponse<>(false, null, "代理商尚未开放任何品牌给您!");
        }

        String[] brands = agent.getAcceptBrand().split(",");

        List<StorageBrand> storageBrands = storageBrandMapper.selectStorageBrandByNames(agentId, brands);
        return new ServiceResponse<>(true, storageBrands, null);
    }

    @Override
    public ServiceResponse<StorageUser> getRecommendBusinessUser(StorageUser storageUser) {
        if (StringUtils.isBlank(storageUser.getSource())) {
            return new ServiceResponse<>(false, null, "当前用不是业务员推荐");
        }
        StorageUser businessUser = storageUserMapper.selectStorageUserByBusinessCode(storageUser.getSource());
        if (businessUser == null) {
            return new ServiceResponse<>(false, null, "推荐人不存在");
        }
        return new ServiceResponse<>(true, businessUser, null);
    }

    @Override
    public ServiceResponse<JSONObject> haveExistsUnConfirmOrderAndUnReadMessage(StorageUser storageUser) {
        Integer unReadCount = storageNoticeMessageMapper.unReadNoticeMessage(storageUser.getPhone());
        Integer unConfirmOrderCount = storageProcurementOrderMapper.unConfirmOrder(storageUser.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", unReadCount > 0);
        jsonObject.put("order", unConfirmOrderCount > 0);
        return new ServiceResponse<>(true, jsonObject, null);
    }

    @Override
    public ServiceResponse<List<JSONObject>> getAgentSelfBrands(StorageUser user, String brandName) {
        Long canOperationUserId = RoleType.getOperationUserId(user.getRole(), user.getId(), user.getShopId());
        Integer applicationType = RoleType.getOwnerType(user.getRole());

        // 查询当前产品的所品牌已经对应品牌下的货号
        StorageProduct condition = new StorageProduct();
        condition.setCreateUserId(canOperationUserId);
        condition.setOwnerType(applicationType);
        if (StringUtils.isNotBlank(brandName)) {
            condition.setClientBrandsList(Arrays.asList(brandName.split(",")));
        }
        List<StorageProduct> products = storageProductMapper.selectStorageProductList(condition);
        if (products == null || products.stream() == null) {
            return new ServiceResponse<>(false, null, "不存在任何品牌");
        }

        List<JSONObject> data = new ArrayList<>();
        Map<String, List<StorageProduct>> map = products.stream().collect(Collectors.groupingBy(StorageProduct::getBrandName));
        map.forEach((key, values) -> {
            JSONObject obj = new JSONObject();
            obj.put("brandName", key);
            obj.put("spuCodeCount", values.size());
            data.add(obj);
        });
        return new ServiceResponse<>(true, data, null);
    }

}
